package org.lgiavedoni.android.franq.core.question.imp;

import java.util.Date;

import lombok.Data;

import org.lgiavedoni.android.franq.core.message.MessageIn;
import org.lgiavedoni.android.franq.core.place.Permanence;
import org.lgiavedoni.android.franq.core.place.Place;
import org.lgiavedoni.android.franq.core.place.dao.PlaceDAO;
import org.lgiavedoni.android.franq.core.position.PositionManager;
import org.lgiavedoni.android.franq.core.question.Question;
import org.lgiavedoni.android.franq.core.speak.CommonPhraseHelper;
import org.lgiavedoni.android.franq.service.communication.CommunicationService;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.date.DateUtil;
import org.lgiavedoni.android.franq.util.place.PlaceUtil;

@Data
public class NameOfPlaceQuestion extends Question {

	private final Place place;

	@Override
	public String getQuestionText() {
		if (PositionManager.inst.getCurrentPosition() != null && PlaceUtil.areTheSamePlace(PositionManager.inst.getCurrentPosition(), place))
			return "What is the name for the current place?";
		else {
			Permanence permanence = place.getLastPermanence();
			StringBuffer question = new StringBuffer();
			Date start, end=null;
			
			if(permanence!=null){
				start = permanence.getCreationDate();
				end = permanence.getEndDate();
			}else{
				start = place.getCreationDate();
			}
			
				question.append("What is the name for the place where we were ");
				if(DateUtil.isToday(start)){
					question.append("today");	
				}else if(DateUtil.isBeforeDay(start)){
					question.append("yesterday");
				}else{
					question.append("on "+DateUtil.getDayOfWeekAsString(start));
				}
				question.append(" from " + DateUtil.getDateHHmm(start));
				if(end!=null)
					question.append(" to: "+DateUtil.getDateHHmm(end)); 
				question.append("?");
			return question.toString();	
		}
	}
 
	@Override
	public boolean process(MessageIn userInfo) {
		Logger.inst.info("Setting the name[" + userInfo.getText() + " to the place[" + place + "]");
		place.setName(userInfo.getText());
		PlaceDAO.inst.update(place);
		setResult(userInfo.getText());
		CommunicationService.inst.sendMessage(CommonPhraseHelper.THANKS);
		return true;
	}

	@Override
	public boolean equals(Question q) {
		return q instanceof NameOfPlaceQuestion && ((NameOfPlaceQuestion) q).getPlace().equals(place);
	}
	@Override
	public boolean isSolved() {
		return super.isSolved() || !place.isUnknowName();
	}
	
	
}
